package com.cropdoctor.config;

import com.cropdoctor.common.Result;
import com.google.gson.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Component
public class DeepSeekClient {

    @Value("${deepseek.api.key}")
    private String apiKey;

    // 修改为beta API端点
    private static final String BETA_API_URL = "https://api.deepseek.com/beta";

    @Autowired
    RedisTemplate redisTemplate;

    public Result<String> callDeepSeek(String prompt) throws IOException {
        Object va = redisTemplate.opsForValue().get(prompt);
        if(va != null) return Result.success((String)va);
        // 使用beta端点
        String endpoint = BETA_API_URL + "/chat/completions";

        // 使用Gson构建JSON请求体
        Gson gson = new Gson();
        JsonObject message = new JsonObject();
        message.addProperty("role", "user");
        message.addProperty("content", prompt);

        JsonObject requestBodyJson = new JsonObject();
        requestBodyJson.addProperty("model", "deepseek-chat");
        requestBodyJson.add("messages", gson.toJsonTree(new JsonObject[]{message}).getAsJsonArray());
        requestBodyJson.addProperty("max_tokens", 1000);
        requestBodyJson.addProperty("temperature", 0.7);
        requestBodyJson.addProperty("stream", false);

        // 创建 HTTP 请求
        HttpPost httpPost = new HttpPost(endpoint);
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
        httpPost.setHeader("Authorization", "Bearer " + apiKey);

        // 使用UTF-8编码创建实体
        String requestBody = requestBodyJson.toString();
        httpPost.setEntity(new StringEntity(requestBody, StandardCharsets.UTF_8));

        // 发送请求并获取响应
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {

            // 获取HTTP状态码
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();

            if (entity == null) {
                throw new IOException("Empty response from DeepSeek API. Status: " + statusCode);
            }

            // 使用UTF-8解析响应
            String responseString = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            // 调试日志：记录原始响应
            System.out.println("DeepSeek API Response: " + responseString);
            responseString = responseString.replace("*", "");
            try {
                // 使用宽松模式解析JSON
                JsonObject jsonResponse = JsonParser.parseString(responseString).getAsJsonObject();

                // 处理API错误
                if (jsonResponse.has("error")) {
                    JsonObject error = jsonResponse.getAsJsonObject("error");
                    String errorMsg = error.has("message") ? error.get("message").getAsString() : "Unknown error";
                    return Result.error("DeepSeek API error: " + errorMsg);
                }

                // 提取回复内容
                if (jsonResponse.has("choices") && jsonResponse.getAsJsonArray("choices").size() > 0) {
                    JsonObject firstChoice = jsonResponse.getAsJsonArray("choices").get(0).getAsJsonObject();
                    if (firstChoice.has("message") && firstChoice.get("message").isJsonObject()) {
                        JsonObject messageObj = firstChoice.getAsJsonObject("message");
                        if (messageObj.has("content")) {
                            String content = messageObj.get("content").getAsString();
                            redisTemplate.opsForValue().set(prompt,content,1, TimeUnit.DAYS);
                            return Result.success(content);
                        }
                    }
                }

                return Result.error("Invalid response format from DeepSeek API");
            } catch (JsonSyntaxException e) {
                // 处理JSON解析错误
                System.err.println("JSON parsing error: " + e.getMessage());
                System.err.println("Response content: " + responseString);
                return Result.error("Invalid JSON response from DeepSeek API");
            }
        } catch (Exception e) {
            // 处理其他异常
            e.printStackTrace();
            return Result.error("Failed to call DeepSeek API: " + e.getMessage());
        }
    }
}